<?php

/**
 * Created by PhpStorm.
 * User: TC
 * Date: 2015/10/22
 * Time: 15:56
 */
//require_once dirname(__FILE__) . '/../db/connectMongoDB.php';
include dirname(__FILE__) . '/../model/peopleModel.php';

class peopleController
{
    public static function AddPeople($peopleArray) {
        $dbname = 'test';
        $host = '127.0.0.1';
        $port = 27017;
        $userName = 'tc';
        $pwd = 'tc199286196988';
        $people = array(
            peopleModel::NAME_FIELD => $peopleArray[peopleModel::NAME_FIELD],
            peopleModel::AGE_FIELD => new MongoInt32($peopleArray[peopleModel::AGE_FIELD]),
            peopleModel::SCHOOL_FIELD => $peopleArray[peopleModel::SCHOOL_FIELD],
            peopleModel::ADDRESS_FIELD => $peopleArray[peopleModel::ADDRESS_FIELD],
            peopleModel::CREATEAT_FIELD => new MongoDate($peopleArray[peopleModel::CREATEAT_FIELD])
        );
        try {
            $mongoClient = new MongoClient("mongodb://$host:$port");
            $mongoDB = $mongoClient->selectDB($dbname);
            $mongoDB->authenticate($userName, $pwd);
            $peopleCollection = $mongoDB->selectCollection(peopleModel::COLLECTION_NAME);
            $result = $peopleCollection->save($people);
            if($result['ok'] == 1) {
                return $people;
            }
        } catch(MongoConnectionException $e) {return 801;}
    }

    public static function GetPeopleList() {
        $dbname = 'test';
        $host = '127.0.0.1';
        $port = 27017;
        $userName = 'tc';
        $pwd = 'tc199286196988';
        try {
            $mongoClient = new MongoClient("mongodb://$host:$port");
            $mongoDB = $mongoClient->selectDB($dbname);
            $mongoDB->authenticate($userName, $pwd);
            $peopleCollection = $mongoDB->selectCollection(peopleModel::COLLECTION_NAME);
            $peoplesArray = $peopleCollection->find()->sort(array(peopleModel::CREATEAT_FIELD => -1));
            foreach($peoplesArray as $key => $people) {
                $people[peopleModel::ID_FIELD] = $people[peopleModel::ID_FIELD]->{'$id'};
            }
            return $peoplesArray;
        } catch (MongoException $e) {
            return 801;
        }
    }
}